package com.example.book.common.configs;

import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.sys.SysDict;
import com.example.book.sys.dict.service.SysDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缓存字典信息
 *
 * @author hcj
 */
@Component
@Order(2)
public class CacheConfig implements ApplicationRunner {

    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${system.crawler.ips}")
    private String ips;

    private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        redisService.flush();
        List<SysDict> list = sysDictService.findList(new SysDict());
        redisService.set("dist", list);

        // 缓存代理IP
        ListOperations operation = redisTemplate.opsForList();

        String[] strings = ips.split(",");

        Map<String, Object> map = null;
        for (String s : strings) {
            map = new HashMap<>();
            String[] ip = s.split(":");
            map.put("ip",ip[0]);
            map.put("port",ip[1]);
            operation.leftPush(Constants.IP_QUEUE, map);
        }

        logger.info("缓存初始化完成！");
    }
}
